package com.common.bus.task;

import com.flux.core.dispatcher.NetworkCallRunnable;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.Response;

/**
 * 基础网络调度的实现
 * Created by cxlin007 on 2017/10/28.
 */

public abstract class BaseNetworkRunnable<R> extends NetworkCallRunnable<R> {

    /**
     * 网络数据数据预处理
     *
     * @param response
     * @return
     * @throws Exception
     */
    protected R handleHttpResponse(Response response) throws Exception {
        String string = response.body().string();
        Class rClass = getRClass();
        HttpResult<R> httpResult = GsonUtils.fromJsonArray(string, rClass);
        if (httpResult.code == 0) {
            return httpResult.data;
        } else {
            throw new HttpException(httpResult.code, new Exception(httpResult.message));
        }
    }

    /**
     * R为：List<T> 或 T
     *
     * @return T.class
     */
    private Class getRClass() {
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        Type typeOne = type.getActualTypeArguments()[0];
        if (typeOne instanceof Class) {
            return (Class) typeOne;

        } else {
            Class tClass = (Class) ((ParameterizedType) type.getActualTypeArguments()[0]).getActualTypeArguments()[0];
            return tClass;
        }
    }

}
